package com.huaxin.common.message;

import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.R;
import com.huaxin.common.message.overlayutil.DrivingRouteOverlay;
import com.huaxin.common.tools.Log;

public class BaiduMapActivity extends BaseActivity implements OnGetRoutePlanResultListener {

    public final static String LOOK = "look";
    public final static String LAT = "latitude";
    public final static String LNG = "longitude";
    public final static String ADR = "address";
    double lat, lng;
    String addr;
    MapView mMapView = null;
    BaiduSDKReceiver mBaiduReceiver;
    MarkerOptions ooA, myPos;
    TextView title, info;
    View infoExtra;
    int routeViewHeight;
    boolean look;//当前浏览模式
    LatLng currentPos, select;
    View routeControl, routeView;
    TextView bottomTitle, bottomInfo, routeLine;
    RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用
    boolean isShowLine = false;
    DrivingRouteOverlay routeOverlay;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_baidumap;
    }

    @Override
    public void initView() {
        mMapView = (MapView) findViewById(R.id.mapView);
        title = (TextView) findViewById(R.id.tv_title);
        info = (TextView) findViewById(R.id.tv_info);
        infoExtra = findViewById(R.id.tv_info_extra);
        routeControl = findViewById(R.id.route_panel);
        routeView = findViewById(R.id.route_view);
        bottomTitle = (TextView) findViewById(R.id.bottom_title);
        bottomInfo = (TextView) findViewById(R.id.bottom_info);
        routeLine = (TextView) findViewById(R.id.route_view_line);
    }

    @Override
    public void initData() {
        if (getIntent() == null) {
            Log.e("NullPointException ");
            finish();
            return;
        }
        final LatLng current = BaseApp.getLatLng();
        lat = getIntent().getDoubleExtra(LAT, current == null ? 0 : current.latitude);
        lng = getIntent().getDoubleExtra(LNG, current == null ? 0 : current.longitude);
        addr = getIntent().getStringExtra(ADR);
        currentPos = select = new LatLng(lat, lng);
        if (TextUtils.isEmpty(addr)) {
            addr = BaseApp.getAddrStr();
        }
        look = getIntent().getBooleanExtra(LOOK, true);
        mBaiduMap = mMapView.getMap();
        if (look) {
            title.setText("位置查看");
//            send.setVisibility(View.GONE);
            info.setVisibility(View.GONE);
            infoExtra.setVisibility(View.GONE);
            findViewById(R.id.bottomView).setVisibility(View.VISIBLE);
            findViewById(R.id.bottom_loc).setVisibility(View.VISIBLE);
            mSearch = RoutePlanSearch.newInstance();
            mSearch.setOnGetRoutePlanResultListener(this);
        } else {
            title.setText("位置选择");
            findViewById(R.id.bottom_loc).setVisibility(View.VISIBLE);
//            send.setVisibility(View.VISIBLE);
        }
        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                point = mBaiduMap.getProjection().toScreenLocation(select);
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                if (!look) {
                    LatLng latLng = mBaiduMap.getProjection().fromScreenLocation(point);
                    if (Math.abs(latLng.longitude - select.longitude) < 0.0001 && Math.abs(latLng.latitude - select.latitude) < 0.0001) {
                    } else {
                        Log.d("onMapStatusChangeFinish...");
                        select = latLng;
                        updateMapView(select, null);
                    }
                }
            }
        });
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(17.0f);
        mMapView.showZoomControls(false);
        mBaiduMap.setMapStatus(msu);
        mMapView.setClickable(true);
        mMapView = new MapView(this,
                new BaiduMapOptions().mapStatus(new MapStatus.Builder()
                        .target(select).build()));
        updateMapView(select, look ? null : addr);
        // 网络异常
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        mBaiduReceiver = new BaiduSDKReceiver();
        registerReceiver(mBaiduReceiver, iFilter);
    }

    private BaiduMap mBaiduMap;
    private Point point;

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            showInfoWindow();
            Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
            return;
        }
//                    route = result.getRouteLines().get(0);
        DrivingRouteOverlay overlay = new RouteHelper.MyDrivingRouteOverlay(mBaiduMap);
        routeOverlay = overlay;
        mBaiduMap.setOnMarkerClickListener(overlay);
        overlay.setData(result.getRouteLines().get(0));
        overlay.addToMap();
        overlay.zoomToSpan();
    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }

    /**
     * 构造广播监听类，监听 SDK key 验证以及网络异常广播
     */
    public class BaiduSDKReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String s = intent.getAction();
            if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
                Log.d("key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置");
            } else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
                Toast.makeText(BaiduMapActivity.this, "网络出错", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        if (mSearch != null) {
            mSearch.destroy();
        }
        unregisterReceiver(mBaiduReceiver);
        super.onDestroy();
    }

    public void onClick(View v) {
        if (v.getId() == R.id.bottom_loc) {
            updateMapView(currentPos, null);
        } else if (v.getId() == R.id.bottom_route) {
            showOrHideRouteInfo(true, 0);
        } else if (v.getId() == R.id.route_view_line) {
            if (isShowLine) {
                if (routeOverlay != null) {
                    routeOverlay.removeFromMap();
                    routeOverlay = null;
                }
                routeLine.setText("显示线路");
            } else {
                PlanNode stNode = PlanNode.withLocation(BaseApp.getLatLng());
                PlanNode enNode = PlanNode.withLocation(select);
                mSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
                routeLine.setText("隐藏线路");
            }
            isShowLine = !isShowLine;
            showOrHideRouteInfo(false, 0);
        } else if (v.getId() == R.id.route_view_qq) {
            showOrHideRouteInfo(false, 1);
        } else if (v.getId() == R.id.route_view_baidu) {
            showOrHideRouteInfo(false, 2);
        } else if (v.getId() == R.id.route_view_gaode) {
            showOrHideRouteInfo(false, 3);
        } else if (v.getId() == R.id.route_view_cancel || v.getId() == R.id.route_panel) {
            showOrHideRouteInfo(false, 0);
        }
    }

    public void back(View v) {
        onBackPressed();
//        finish();
//        overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }

    boolean froceSend = false;

    public void sendLocation(View view) {
        if (TextUtils.isEmpty(ooA.getTitle())) {
            froceSend = true;
        } else {
            send();
        }
    }

    void updateMarkView(final boolean needSend) {
        GeoCoder geoCoder = GeoCoder.newInstance();
        //发起反地理编码请求(经纬度->地址信息)
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(ooA.getPosition()));
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                if (look) {
                    bottomTitle.setText(arg0.getAddressDetail().street + arg0.getAddressDetail().streetNumber);
                    bottomInfo.setText(arg0.getAddress()+arg0.getSematicDescription());
                } else {
                    addr = arg0.getAddress()+arg0.getSematicDescription();
                    ooA.title(addr);
//                Log.d("address=" + addr);
                    info.setText(addr);
                    if (needSend || froceSend) {
                        froceSend = false;
                        send();
                    }
                }
            }

            @Override
            public void onGetGeoCodeResult(GeoCodeResult arg0) {
            }
        });
    }

    void send() {
        Intent intent = BaiduMapActivity.this.getIntent();
        final LatLng latLng = ooA.getPosition();
        intent.putExtra(LAT, latLng.latitude);
        intent.putExtra(LNG, latLng.longitude);
        intent.putExtra(ADR, ooA.getTitle());
        BaiduMapActivity.this.setResult(RESULT_OK, intent);
        onBackPressed();
//        finish();
//        overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }

    void updateMapView(LatLng llA, String addr) {
        mBaiduMap.clear();
//        CoordinateConverter converter = new CoordinateConverter();
//        converter.coord(llA);
//        converter.from(CoordinateConverter.CoordType.COMMON);
//        LatLng convertLatLng = converter.convert();
        if (ooA == null) {
            ooA = new MarkerOptions().icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.ease_icon_marka))
                    .zIndex(4);
        }
        ooA.position(llA);
        mBaiduMap.addOverlay(ooA);
        if (routeOverlay != null) {
            routeOverlay.addToMap();
        }
        final MapStatusUpdate u;
        if (look) {
            //浏览模式额外显示我当前的位置
            if (myPos == null) {
                myPos = new MarkerOptions().icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.mypos))
                        .zIndex(4);
            }
            if (BaseApp.getLatLng() == null) {
                Toast.makeText(this,"无法定位您的位置",Toast.LENGTH_SHORT).show();
            } else {
                myPos.position(BaseApp.getLatLng());
                mBaiduMap.addOverlay(myPos);
            }
            LatLngBounds bounds = new LatLngBounds.Builder().include(myPos.getPosition()).include(llA).build();
//        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(bounds, 17.0f);
            u = MapStatusUpdateFactory.newLatLngBounds(bounds);
        } else {
            u = MapStatusUpdateFactory.newLatLngZoom(llA, 17.0f);
        }
        mBaiduMap.animateMapStatus(u);
//        if (look) {
//            mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(16));
//        }
        if (addr == null) {
            updateMarkView(false);
        } else {
            ooA.title(addr);
            info.setText(addr);
        }
    }

    void showInfoWindow() {
    }

    void showOrHideRouteInfo(final boolean show, final int id) {
        if (routeViewHeight == 0) {
            int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            routeView.measure(0, height);
            routeViewHeight = routeView.getMeasuredHeight();
        }
        final ObjectAnimator animator;
        if (show) {
            routeControl.setVisibility(View.VISIBLE);
            animator = ObjectAnimator.ofFloat(routeView, "translationY", routeViewHeight, 0);
        } else {
            routeControl.postDelayed(new Runnable() {
                @Override
                public void run() {
                    routeControl.setVisibility(View.GONE);
                    if (id > 0) {
                        startNavi(id);
                    }
                }
            }, 300);
            animator = ObjectAnimator.ofFloat(routeView, "translationY", 0, routeViewHeight);
        }
        animator.setDuration(300);
        animator.start();
    }

    void startNavi(int id) {
        if (id == 1) {
            if (BaseApp.getLatLng() == null || select == null) {
                Toast.makeText(this,"正在获取您的位置,请稍等",Toast.LENGTH_SHORT).show();
            }
            MapHelper.startTencentNavi(this, BaseApp.getLatLng(), BaseApp.getAddrStr(), select, bottomInfo.getText().toString());
        } else if (id == 2) {
            if (BaseApp.getLatLng() == null || select == null) {
                Toast.makeText(this,"正在获取您的位置,请稍等",Toast.LENGTH_SHORT).show();
            }
            MapHelper.startBaiduMapNavi(this, BaseApp.getLatLng(), BaseApp.getAddrStr(), select, bottomInfo.getText().toString());
        } else if (id == 3) {
            MapHelper.startGaoDeNavi(this, select, bottomInfo.getText().toString());
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
